package com.wyj.controller;

import com.wyj.event.EventProducer;
import com.wyj.pojo.User;
import com.wyj.pojo.event;
import com.wyj.service.imp.LikeServiceImp;
import com.wyj.util.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.HashMap;
import java.util.Map;

/**
 * @author 王永杰
 * @Description 描述该类的做什么用
 * @since 2022/7/26
 */
@Controller
public class LikeController implements CommunityConstant {

    @Autowired
    LikeServiceImp likeServiceImp;

    @Autowired
    HostHolder hostHolder;

    @Autowired
    RedisUtil redisUtil;

    @Autowired
    EventProducer eventProducer;

    @RequestMapping(value = "/like",method = RequestMethod.POST)
    @ResponseBody
    public String like(int entityType,int entityId,int entityUserId,int postId) {

        User user = hostHolder.getUser();

        //获取key
        String entityLikeKey = RedisKeyUtil.getEntityLikeKey(entityType, entityId);
        //点赞
        likeServiceImp.like(user.getId(),entityType,entityId,entityUserId);

        //获取点赞的数量
        long entityLikeCount = likeServiceImp.findEntityLikeCount(entityType, entityId);

        //获取点赞的状态
        int entityLikeStatus = likeServiceImp.findEntityLikeStatus(user.getId(), entityType, entityId);

        //获取某个用户被点赞的数量
        int userLikeCount = likeServiceImp.findUserLikeCount(entityUserId);

        //计算分数
        String postScore = RedisKeyUtil.getPostScore();
        redisUtil.sSet(postScore,entityId);

        Map<String, Object> map = new HashMap<>();
        map.put("likeCount",entityLikeCount);
        map.put("likeStatus",entityLikeStatus);

        //触发点赞事件
        if (entityLikeStatus == 1) {
            event event = new event();
            event.setTopic(TOPIC_LIKE);
            event.setUserId(user.getId());
            event.setEntityType(entityType);
            event.setEntityUserId(entityUserId);
            event.setEntityId(entityId);
            event.setData("postId",postId);

            //将事件放到主题当中
            eventProducer.fireEvent(event);
        }



        return CommunityUtil.getJsonString(0,null,map);
    }

}
